package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.KHUtil

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONObject
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiTaskIssued*
 * @Description: 电销任务下发接口-按线程号
 * @Author: tian*
 * @Date 2022/6/24 18:03
 *
 */
class apiTaskAssignDx implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiTaskAssignDx.class);

    //根据线程号获取待下发任务
    String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        // 初始化返回参数
        String Syncpram = "";
        JSONObject result = new JSONObject();
        String getMethod = request.getMethod();
        if (getMethod.equals("GET")) {
            Syncpram = request.getQueryString();
            log.info("接收调用GET参数信息：" + Syncpram);
        } else if (getMethod.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                Syncpram += line;
            }
            log.info("接收调用POST报文信息：" + Syncpram);
        }
        String threadid = request.getParameter("threadid"); //传入线程号
        String TGuid = request.getParameter("TGuid"); //传入唯一执行标识

        String explanflag=threadid+"|"+TGuid;
        log.debug("--------本次apiTaskAssignDx任务执行标识："+explanflag+"--------");
        try {
            int loogNum = 0; //总数量
            int succNum = 0; //成功数量
            int failNum = 0; //失败数量
            long totalTime = System.currentTimeMillis();
            //根据线程号查询是否存在任务未下发
            List accountList = eliteBean.chaxun_sql("select ifnull(a.rec_id,'') as rec_id,ifnull(a.customerid,'') as customerid,ifnull(a.task_type,'') as task_type,ifnull(a.task_guid,'') as task_guid,ifnull(p.task_name,'') as code_name,ifnull(a.mobile,'') as taskmobile,ifnull(a.f_register_time,'') as f_register_time from Account_Information a  left join pa_sms_task_batch p on p.rec_guid=a.thread_id  where a.deal_flag=0 and thread_id='" + threadid + "' limit 300", "dataSource");
            loogNum = accountList.size();
            log.debug("标识为:"+explanflag+"的任务本次待执行条数"+loogNum);
            for (int i = 0; i < loogNum; i++) {
                long startTime = System.currentTimeMillis();
                String rule_rec_id = "";
                String r_Rolegroup_Id = "";
                String r_Staff_Id = "";
                int deal_flag = 0;
                String deal_result = "";
                String rec_id = "";
                String investorid = "";
                String channel="";
                String customer_guid="";
                try {
                    //步骤一：获取任务表待执行任务信息
                    Map accountMap = accountList.get(i);
                    rec_id = accountMap.get("rec_id") == null ? '':accountMap.get("rec_id");//处理任务主键
                    String task_type = accountMap.get("task_type")== null ? '':accountMap.get("task_type");//任务类型编号
                    String node_id = "0PEKLS";//任务类型对应的工单node_id
                    String code_name = accountMap.get("code_name")== null ? '':accountMap.get("code_name");//任务类型名称
                    String taskmobile = accountMap.get("taskmobile")== null ? '':accountMap.get("taskmobile");//任务记录表的手机号码
                    String f_register_time = accountMap.get("f_register_time")== null ? '':accountMap.get("f_register_time");//任务记录表的注册时间，取自界面配置的表中
                    log.debug("开始执行标识为:"+explanflag+"|手机号为："+taskmobile+"|注册时间为"+f_register_time+"的下发任务");

                    //步骤二：获取待执行任务对应的客户信息
                    String registerPhoneSql = "select ifnull(f_phone,'') as f_phone,ifnull(creat_date,'') as creat_date,ifnull(cust_channel,'') as cust_channel,ifnull(f_channel,'') as f_channel,ifnull(f_xf_channel,'') as f_xf_channel,ifnull(f_cloud_state,'') as f_cloud_state,ifnull(f_cloud_platform_state,'') as f_cloud_platform_state,ifnull(f_cloud_complex_state,'') as f_cloud_complex_state,ifnull(f_register_time,'') as f_register_time,ifnull(f_elector_name,'') as f_elector_name,ifnull(opendate,'') as opendate,ifnull(investortype,'') as investortype,ifnull(investorid,'') as investorid,ifnull(f_cust_feed_back,'') as f_cust_feed_back,ifnull(f_type_name,'') as f_type_name,ifnull(f_dic_name,'') as f_dic_name,ifnull(f_status,'') as f_status,ifnull(f_operation_step,'') as f_operation_step,ifnull(f_last_operation_time,'') as f_last_operation_time from dws.register_phone where f_phone='" + taskmobile + "'  limit 1";
                    List registerPhoneList = eliteBean.chaxun_sql(registerPhoneSql, "dataSource");
                    int custSize=registerPhoneList.size();
                    log.debug("执行标识为："+explanflag+"|手机号："+taskmobile+"|注册时间:"+f_register_time+"|对应的register_phone中的客户数量为："+custSize);
                    if (custSize> 0) {
                        String mobile =registerPhoneList.get(0).get("f_phone") ==null?'':registerPhoneList.get(0).get("f_phone");//联系号码
                        channel = registerPhoneList.get(0).get("f_channel")== null ? '':registerPhoneList.get(0).get("f_channel");//渠道id
                        String f_xf_channel = registerPhoneList.get(0).get("f_xf_channel")== null ? '':registerPhoneList.get(0).get("f_xf_channel");//细分渠道
                        String f_cloud_state = registerPhoneList.get(0).get("f_cloud_state")== null ? '':registerPhoneList.get(0).get("f_cloud_state");//云平台状态
                        String opendate = registerPhoneList.get(0).get("opendate")== null ? '':registerPhoneList.get(0).get("opendate");//开户时间
                        String f_operation_step = registerPhoneList.get(0).get("f_operation_step")== null ? '':registerPhoneList.get(0).get("f_operation_step");//操作步骤
                        String f_last_operation_time = registerPhoneList.get(0).get("f_last_operation_time")== null ? '':registerPhoneList.get(0).get("f_last_operation_time");//操作时间
                        investorid = registerPhoneList.get(0).get("investorid")== null ? '':registerPhoneList.get(0).get("investorid");//资金账号
                        String creat_date = registerPhoneList.get(0).get("creat_date")==''?null: registerPhoneList.get(0).get("creat_date"); //预约时间
                        log.debug("执行标识为："+explanflag+"的任务手机号码为："+mobile+"|渠道："+channel+"|细分渠道"+f_xf_channel+"|预约时间："+creat_date);


                        //步骤三：查询customer表数据核实是否存在,不存在则新增，存在则将register_phone表的客户信息更新到customer表中
                        String checkCustSql = "select customer_guid from customer where mobile='"+taskmobile+"' limit 1";
                        List checkCustRes = eliteBean.chaxun_sql(checkCustSql, "dataSource");
                        if (checkCustRes.size() > 0) {
                            Map checkTaskMap = checkCustRes.get(0);
                            customer_guid = checkTaskMap.get("customer_guid");
                            //按照register_phone修改客户信息表编号customer_guid的数据，查询采用手机号码+注册时间

                            if(creat_date==null){
                                String custTaskUpdateSQL1 = "update customer set channel='" + channel + "',f_xf_channel='" + f_xf_channel + "',f_cloud_state='" + f_cloud_state + "',open_account='" + opendate + "',register_time='" + f_register_time + "',f_operation_step='" + f_operation_step + "',f_last_operation_time='" + f_last_operation_time + "',customer_id='" + investorid + "',MODIFIEDBY='SELITE',MODIFIEDDATE=now() where Customer_Guid='" + customer_guid + "'";
                                eliteBean.update(custTaskUpdateSQL1, "dataSource");
                                log.debug("没有预约时间"+taskmobile);
                            }else{
                                String custTaskUpdateSQL2 = "update customer set channel='" + channel + "',f_xf_channel='" + f_xf_channel + "',f_cloud_state='" + f_cloud_state + "',open_account='" + opendate + "',register_time='" + f_register_time + "',f_operation_step='" + f_operation_step + "',f_last_operation_time='" + f_last_operation_time + "',customer_id='" + investorid + "',MODIFIEDBY='SELITE',MODIFIEDDATE=now(),appointment_time='" + creat_date + "' where Customer_Guid='" + customer_guid + "'";
                                eliteBean.update(custTaskUpdateSQL2, "dataSource");
                                log.debug("有预约时间"+taskmobile);
                            }
                        }else{
                            //按照register_phone新增客户信息，查询采用手机号码+注册时间
                            String Temp_Guid1 = KHUtil.getRandomString(31).toUpperCase();
                            String new_Customer_Guid = "Cust_" + Temp_Guid1;
                            customer_guid = new_Customer_Guid;
                            if(creat_date==null){
                                log.debug("没有预约时间"+taskmobile);
                                eliteBean.update("insert into customer(customer_guid,channel,f_xf_channel,mobile,f_cloud_state,open_account,register_time,CREATEDBY,CREATEDDATE,MODIFIEDBY,MODIFIEDDATE,f_operation_step,f_last_operation_time)values('" + new_Customer_Guid + "','" + channel + "','" + f_xf_channel + "','" + mobile + "','" + f_cloud_state + "','" + opendate + "','" + f_register_time + "','SELITE',now(),'SELITE',now(),'" + f_operation_step + "','" + f_last_operation_time + "')", "dataSource");
                            }else{
                                log.debug("有预约时间"+taskmobile);
                                eliteBean.update("insert into customer(customer_guid,appointment_time,channel,f_xf_channel,mobile,f_cloud_state,open_account,register_time,CREATEDBY,CREATEDDATE,MODIFIEDBY,MODIFIEDDATE,f_operation_step,f_last_operation_time)values('" + new_Customer_Guid + "','" + creat_date + "','" + channel + "','" + f_xf_channel + "','" + mobile + "','" + f_cloud_state + "','" + opendate + "','" + f_register_time + "','SELITE',now(),'SELITE',now(),'" + f_operation_step + "','" + f_last_operation_time + "')", "dataSource");

                            }
                        }



                        //20250722当断点名单下发时,判断是否有该客户当天是否有促开名单,有则不下发,没有就下发断点名单
                        if (!KHUtil.isNull(customer_guid)) {
                            String checkyyListSql='''Select e.HANDLEGROUP_ID,e.HANDLEBY_ID From elitetask e
                                        left join customer c on e.customer_guid=c.customer_guid
                                        where e.map_id='4CA2PP'   And  Date_Format(c.appointment_time, '%Y-%m-%d') = Date_Format(Now(), '%Y-%m-%d')
                                        AND e.CUSTOMER_GUID=? LIMIT 1 ''';
                            List<Map<String, Object>> KhList = jt.queryForList(checkyyListSql,customer_guid);
                              if (KhList.size()>0){
                                  deal_flag = -2;
                                  deal_result = "下发失败-当断点名单下发时,判断是否有该客户当天有促开名单,有则不下发";
                                  long endTime = System.currentTimeMillis();
                                  String reOutIntermediarySql = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = " + deal_flag + ", Deal_Result = '" + deal_result + "-耗时:" + (endTime - startTime) + "' Where Rec_Id = '" + rec_id + "'";
                                  eliteBean.update(reOutIntermediarySql, "dataSource");
                                  continue;
                              }
                        }



                        //步骤四：开始下发任务流程
                        if (!KHUtil.isNull(customer_guid)) {
                            //步骤五：使用资金账号校验是否存在与资金账号同类型的任务
                            String checkSameTask = "select e.elitetask_guid from elitetask e   where e.customer_guid='" + customer_guid + "'  and e.PA_TASKTYPE='" + task_type + "' limit 1";
                            List checkTaskRes = eliteBean.chaxun_sql(checkSameTask, "dataSource");
                            if (checkTaskRes.size() > 0) {
                                Map checkTaskMap = checkTaskRes.get(0);
                                String checkTask = checkTaskMap.get("elitetask_guid");
                                deal_flag = -1;
                                deal_result = "下发失败-手机号:" + taskmobile + ",已存在相同类型的" + code_name + "编号为："+checkTask+"当前任务无需再次下发";
                            }else {
                                // 查询是否存在电销促开的任务 ,如果有则将组别人员赋值给该任务的组别 人员
                                List ApwList=eliteBean.chaxun_sql("Select e.HANDLEGROUP_ID,e.HANDLEBY_ID,s.WORKSTATUS,s.DEFAULTROLEGROUP From elitetask e\n" +
                                        "left join staff s on e.HANDLEBY_ID=s.STAFF_ID\n" +
                                        "where e.map_id='4CA2PP' \n" +
                                        "AND CUSTOMER_GUID='"+customer_guid+"' LIMIT 1 ","dataSource");
                                String  WORKSTATUS=null;
                                String DEFAULTROLEGROUP=null;
                                //LMGVGI
                                if(ApwList.size()>0){
                                    r_Rolegroup_Id=ApwList.get(0).get("HANDLEGROUP_ID");
                                    r_Staff_Id=ApwList.get(0).get("HANDLEBY_ID");
                                     WORKSTATUS=ApwList.get(0).get("WORKSTATUS");
                                    DEFAULTROLEGROUP=ApwList.get(0).get("DEFAULTROLEGROUP");
                                    //判断是否离职
                                    if(WORKSTATUS=="QUIT"){
                                    }else{
                                    log.debug("本次断点任务分配给人员："+r_Staff_Id+"---组别："+r_Rolegroup_Id);
                                    }
                                }

                                if(ApwList.size()<=0||WORKSTATUS=="QUIT"||DEFAULTROLEGROUP!="LMGVGI"){
                                //步骤六：重复名单校验通过，按照名单信息中渠道在规则表中找到优先级最高的规则对应的坐席
                                List ruleCheckList;
                                String ruleCheckSQL = "Select Rule_Id, Rule_Name, Rolegroup, Staff_Id, Order_Adjustment From Hst_Rule_Issue Where Rule_State = 1 And Find_In_Set('" + channel + "', Code_Id) > 0  and department_flag=2 Order By Order_Adjustment Limit 1";
                                ruleCheckList = eliteBean.chaxun_sql(ruleCheckSQL, "dataSource");
                                if (ruleCheckList.size() <= 0) {
                                    //优先根据渠道查询，如根据渠道未查询到规则，则查询电销规则中优先级最高的一条规则，最高规则为默认规则
                                    String ruleCheckSQL1 = "Select Rule_Id, Rule_Name, Rolegroup, Staff_Id, Order_Adjustment From Hst_Rule_Issue Where Rule_State = 1   and department_flag=2 Order By Order_Adjustment Limit 1";
                                    ruleCheckList = eliteBean.chaxun_sql(ruleCheckSQL1, "dataSource");
                                }
                                if (ruleCheckList.size() > 0) {
                                    Map ruleCheckMap = ruleCheckList.get(0);
                                    String Rule_Id = ruleCheckMap.get("Rule_Id");
                                    String Rule_Name = ruleCheckMap.get("Rule_Name");
                                    String Rolegroup = ruleCheckMap.get("Rolegroup");
                                    String Staff_Id = ruleCheckMap.get("Staff_Id");
                                    String Order_Adjustment = ruleCheckMap.get("Order_Adjustment");
                                    log.debug("规则ID:" + Rule_Id + " 规则名:" + Rule_Name + " 下发组:" + Rolegroup + " 下发人:" + Staff_Id + " 优先级:" + Order_Adjustment);
                                    // 初始化规则下发
                                    ruleAssignInit(eliteBean, Rule_Id, channel);
                                    // 默认平均分配，取当前名单下发最少的坐席（不支持一人多组）
                                    def getAverageStaffSQL = "Select R1.Rec_Id, R2.Rolegroup_Id, R1.Staff_Id, R3.counselor_id From Hst_Rule_Issue_Control R1 Left Join Staffrolegroup R2 On R1.Staff_Id = R2.Staff_Id Left Join Staff R3 On R1.Staff_Id = R3.Staff_Id Where Rule_Id = " + Rule_Id + " And Assign_Date = Date_Format(Now(), '%Y-%m-%d') Order By Assign_Num,Staff_Id Limit 1";
                                    List getAverageStaffList = eliteBean.chaxun_sql(getAverageStaffSQL, "dataSource");
                                    if (getAverageStaffList.size() > 0) {
                                        Map getAssginStaffMap = getAverageStaffList.get(0);
                                        rule_rec_id = getAssginStaffMap.get("Rec_Id");
                                        r_Rolegroup_Id = getAssginStaffMap.get("Rolegroup_Id");
                                        r_Staff_Id = getAssginStaffMap.get("Staff_Id");

                                        if(WORKSTATUS=="QUIT"||DEFAULTROLEGROUP!="LMGVGI"){
                                            String[] TaskDealSQL = new String[2];
                                            //如果预约的任务人员是离职状态,那么将预约的任务处理人和处理组,修改成当前要下发的处理人处理组
                                            TaskDealSQL[0]="Update Elitetask set HANDLEGROUP_ID='"+r_Rolegroup_Id+"',HANDLEBY_ID='"+r_Staff_Id+"' where Customer_guid='"+customer_guid+"' and Map_id='4CA2PP' ";
                                            TaskDealSQL[1]="Update objective set HANDLEGROUP_ID='"+r_Rolegroup_Id+"',HANDLEBY_ID='"+r_Staff_Id+"' where Customer_guid='"+customer_guid+"' and Map_id='4CA2PP' ";
                                            int[] batchSQLResult = eliteBean.updateBatch(TaskDealSQL, "dataSource");
                                            if(WORKSTATUS=="QUIT"){

                                                log.debug("【查询到当前名单预约任务处理人已经离职】[将修改人员]："+r_Staff_Id+"---[修改的组别：]"+r_Rolegroup_Id+"----[处理批次SQL状态--->]"+batchSQLResult.toString());

                                            }else if (DEFAULTROLEGROUP!="LMGVGI"){
                                                log.debug("【查询到当前名单预约任务处理人默认组已经不是电销】[将修改人员]："+r_Staff_Id+"---[修改的组别：]"+r_Rolegroup_Id+"----[处理批次SQL状态--->]"+batchSQLResult.toString());

                                            }

                                        }
                                    } else {
                                        r_Rolegroup_Id = '';
                                        r_Staff_Id = '';
                                        log.debug("[当前名单下发人信息]无组别人员 默认不分配 进入未分配数据池！");
                                    }
                                } else {
                                    r_Rolegroup_Id = '';
                                    r_Staff_Id = '';
                                    log.debug("[当前名单下发人信息]无组别人员 默认不分配 进入未分配数据池！");
                                }
                                }
                                //步骤七：按照找到的坐席开始创建任务
                                Map newCustomerManagerMap1 = newCustomerDeal(eliteBean, r_Rolegroup_Id, r_Staff_Id, node_id, "", customer_guid, task_type, rule_rec_id, taskmobile, investorid);
                                deal_flag = newCustomerManagerMap1.get("deal_flag").toInteger();
                                deal_result = newCustomerManagerMap1.get("deal_result");
                            }
                        } else {
                            deal_flag = -2;
                            deal_result = "下发失败-根据手机号在集中作业平台未匹配到客户信息或当前任务手机号为空" + taskmobile;
                        }
                    }else{
                        log.debug("执行标识为："+explanflag+"|手机号："+taskmobile+"|注册时间:"+f_register_time+"的任务在register_phone表中为找到对应的客户信息");
                        deal_flag = -1;
                        deal_result = "下发失败-手机号:" + taskmobile + "未匹配到对应的客户信息";
                    }
                } catch (Exception e) {
                    deal_flag = -1;
                    deal_result = "下发失败-当前任务下发时异常" + e.getMessage();
                    log.error("【执行结束】当前名单" + i + " 执行处理异常!", e);
                }

                //步骤八：更新任务处理历史表
                long endTime = System.currentTimeMillis();
                String reOutIntermediarySql = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = " + deal_flag + ", Deal_Result = '" + deal_result + "-耗时:" + (endTime - startTime) + "' Where Rec_Id = '" + rec_id + "'";
                eliteBean.update(reOutIntermediarySql, "dataSource");
                log.debug("【执行结束】本次耗时:" + (endTime - startTime));

                //步骤九：统计执行数量
                if (deal_flag == 1) {
                    succNum++;
                } else if (deal_flag == -1||deal_flag == -2) {
                    failNum++;
                }
            }
            String Result = "电销任务数据处理完成,总数:" + loogNum + " 成功数量:" + succNum + " 失败数量:" + failNum + "-处理时长(毫秒):" + (System.currentTimeMillis() - totalTime);
            result.put("code", "1");
            result.put("msg", Result);
        } catch (Exception e) {
            log.error("处理异常!", e);
            result.put("code", "-1");
            result.put("msg", "电销下发任务-按线程号处理异常-线程号:" + threadid + "，" + e.printStackTrace());
        }
        log.debug("执行标识为"+explanflag+"的本次全部任务结果："+result.toString());
        return result.toString();
    }

    //将任务下发至对应的坐席
    public static Map<String, String> newCustomerDeal(EliteBean eliteBean, String r_Rolegroup_Id, String r_Staff_Id, String node_id, String Objective_Guid, String Customer_Guid, String task_type, String Rec_Id, String mobile, String customer_id) {
        Map<String, String> map = new HashMap<String, String>();
        // 生成相关ID
        String Temp_Guid = KHUtil.getRandomString(31).toUpperCase();
        String re_Objective_Guid = "";

        if (Objective_Guid == "") {

            re_Objective_Guid = "OBJE_" + Temp_Guid;
        } else {
            re_Objective_Guid = Objective_Guid;
        }
        String EliteTask_Guid = "TASK_" + Temp_Guid;
        String[] custTaskDealSQL = new String[6];

        try {
            if (Objective_Guid == '' || Objective_Guid == null) {
                // 插入Objective表
                custTaskDealSQL[1] = "Insert Into Objective" +
                        "  (Objective_Guid," +
                        "   Objectivetype_Id," +
                        "   Handleby_Id," +
                        "   Handlegroup_Id," +
                        "   Priority_Id," +
                        "   Expireddate," +
                        "   Customer_Guid," +
                        "   Objectivestatus," +
                        "   Iscontact," +
                        "   Trytimes," +
                        "   Successfulcontacttimes," +
                        "   Createdby," +
                        "   Createddate," +
                        "   Obstatus," +
                        "   Failure_Attempt," +
                        "   Contact_Customer_Guid," +
                        "   Passflag," +
                        "   Lastassigndate," +
                        "   Failstatus," +
                        "   Successstatus," +
                        "   Owner," +
                        "   Workorderframe_Id," +
                        "   Category," +
                        "   Forecastdate," +
                        "   Workorderid," +
                        "   Workordertype1," +
                        "   Workordertype2," +
                        "   Workordertype3," +
                        "   Workordertype4," +
                        "   Objectivesubstatus," +
                        "   Map_Id," +
                        "   Curstep_Id_Map," +
                        "   Max_Attempt," +
                        "   Nocontacttry," +
                        "   Allocation_Pool," +
                        "   Appointment," +
                        "   PA_TASKTYPE)" +
                        "Values" +
                        "  ('" + re_Objective_Guid + "'," +
                        "   'RE0TX1'," +
                        "   '" + r_Staff_Id + "'," +
                        "   '" + r_Rolegroup_Id + "'," +
                        "   'NORMAL'," +
                        "   Date_Add(Now(), Interval 1 Day)," +
                        "   '" + Customer_Guid + "'," +
                        "   'OPEN'," +
                        "   0," +
                        "   0," +
                        "   0," +
                        "   'SELITE'," +
                        "   Now()," +
                        "   'OPEN'," +
                        "   999," +
                        "   ''," +
                        "   0," +
                        "   Null," +
                        "   '0'," +
                        "   '0'," +
                        "   ''," +
                        "   '4G3CCS'," +
                        "   'CASE'," +
                        "   now()," +
                        "   Concat('PA', Date_Format(Now(), '%Y%m%d%H'), '-', Lpad(Floor(Rand() * 10000), 4, '0'))," +
                        "   ''," +
                        "   ''," +
                        "   ''," +
                        "   ''," +
                        "   'OPEN'," +
                        "   '4G3CCS'," +
                        "   '" + node_id + "'," +
                        "   0," +
                        "   0," +
                        "   0," +
                        "   0," +
                        "   '" + task_type + "')";
            }
            // 插入EliteTask表
            custTaskDealSQL[2] = "Insert Into Elitetask" +
                    "  (Elitetask_Guid," +
                    "   Objective_Guid," +
                    "   Objectivetype_Id," +
                    "   Expectstarttime," +
                    "   Expectendtime," +
                    "   Obstatus," +
                    "   Recordstatus," +
                    "   Attempt," +
                    "   Max_Attempt," +
                    "   Handleby_Id," +
                    "   Handlegroup_Id," +
                    "   Createdby," +
                    "   Createddate," +
                    "   Failure_Attempt," +
                    "   Comments," +
                    "   Customer_Guid," +
                    "   Localtrycount," +
                    "   Lastassigndate," +
                    "   Workorderframe_Id," +
                    "   Curstepstatus," +
                    "   Curstep_Id," +
                    "   Stepforecastdate," +
                    "   Curstep_Id_Map," +
                    "   Map_Id," +
                    "   Objectivesubstatus," +
                    "   Elitetaskstatus," +
                    "   Obflag,Maintaskstep_Id_Map," +
                    "   PA_TASKTYPE)" +
                    "Values" +
                    "  ('" + EliteTask_Guid + "'," +
                    "   '" + re_Objective_Guid + "'," +
                    "   'RE0TX1'," +
                    "   Now()," +
                    "   Date_Add(Now(), Interval 3 Day)," +
                    "   'OPEN'," +
                    "   0," +
                    "   0," +
                    "   999," +
                    "   '" + r_Staff_Id + "'," +
                    "   '" + r_Rolegroup_Id + "'," +
                    "   'SELITE'," +
                    "   Now()," +
                    "   999," +
                    "   ''," +
                    "   '" + Customer_Guid + "'," +
                    "   0," +
                    "   Now()," +
                    "   ''," +
                    "   'OPEN'," +
                    "   '0PEKLS'," +
                    "   Now()," +
                    "   '" + node_id + "'," +
                    "   '4G3CCS'," +
                    "   'OPEN'," +
                    "   'OPEN'," +
                    "   1,'','" + task_type + "')";

            //渠道规则均分
            if (Rec_Id != "" && Rec_Id != null) {
                custTaskDealSQL[3] = "Update Hst_Rule_Issue_Control Set Assign_Num = Assign_Num + 1, Last_Check_Time = Now() Where Rec_Id = " + Rec_Id;
            }
            //新增分配历史
            custTaskDealSQL[5] = "insert into hst_Service_hislist(sys_guid,CUSTOMER_ID,customer_guid,used_staffid,apply_time,MODIFIEDBY,context,Reviewer_staffid,Reviewer_time,customer_phone) VALUES(uuid(),'" + customer_id + "','" + Customer_Guid + "','" + r_Staff_Id + "',now(),'SELITE','电销配置任务自动下发','SELITE',now(),'" + mobile + "') ";

            int[] batchSQLResult = eliteBean.updateBatch(custTaskDealSQL, "dataSource");
            map.put("deal_flag", "1");
            map.put("deal_result", "下发成功-手机号:" + mobile + ",本次下发任务分配至" + r_Staff_Id);
            log.debug("新客户入库批量处理SQL返回结果：" + batchSQLResult.toString());    
        } catch (Exception e) {
            log.error("新客户入库异常!", e);
            map.put("deal_flag", "-1");
            map.put("deal_result", "下发失败-手机号:" + mobile + ",下发任务异常" + e.printStackTrace());
        }
        return map;
    }

    //规则下发数据初始化
    public static boolean ruleAssignInit(EliteBean eliteBean, String Rule_Id, String channel) {
        boolean reFlag = true;
        //新增判断坐席B岗接任时间的逻辑截止状态、及离职人员默认不分配
        //A.-如果有离职人员 则直接关闭其分配状态-- 是否开启自动分配 0开启 1关闭
        String updatestaffstate1SQL = '''Update Staff
                                           Set Auto_Allocation = 1
                                         Where Auto_Allocation = 0
                                           And Workstatus != 'ONLINE\'''';
        eliteBean.update(updatestaffstate1SQL, "dataSource");

        //B.-如果有B岗角色接任时间到期 则更新企状态为自动开启分配 +清空时间维护
        String updatestaffstate2SQL = '''Update Staff
                                           Set Auto_Allocation = 0, Starttime = Null, Endtime = Null
                                         Where Auto_Allocation = 1
                                           And Starttime < Now()
                                           And Endtime < Now()''';
        eliteBean.update(updatestaffstate2SQL, "dataSource");

        // 初始化（1~4）下发记录表（这里默认按每天清零）
        // 1-查找当前规则配置的坐席
        String ruleStaffSQL = "Select Case" +
                "         When R1.Staff_Id Is Null Or R1.Staff_Id = '' Then" +
                "          R2.Staff_Id" +
                "         Else" +
                "          R1.Staff_Id" +
                "       End As ruleStaff" +
                "  From Hst_Rule_Issue R1" +
                "  Left Join (Select R4.Rule_Id, Group_Concat(Distinct R3.Staff_Id) As Staff_Id" +
                "               From Rolegroup R1" +
                "               Left Join Staffrolegroup R2" +
                "                 On R1.Rolegroup_Id = R2.Rolegroup_Id" +
                "               Left Join Staff R3" +
                "                 On R2.Staff_Id = R3.Staff_Id" +
                "               Left Join Hst_Rule_Issue R4" +
                "                 On Find_In_Set(R1.Rolegroup_Id, R4.Rolegroup) > 0" +
                "              Where R1.Status = 1" +
                "                And ((R3.auto_allocation = 0) " +
                " 				or (R3.auto_allocation = 1 And R3.starttime>now() And R3.endtime>now() And R3.starttime is not null And R3.endtime is not null)" +
                " 				or (R3.auto_allocation = 1 And R3.starttime<now() And R3.endtime<now() And R3.starttime is not null And R3.endtime is not null))" +
                "                And R3.Workstatus = 'ONLINE'" +
                "                And R4.Rule_Id = " + Rule_Id + " and department_flag=2) R2" +
                "    On R1.Rule_Id = R2.Rule_Id" +
                "   And (R1.Staff_Id Is Null Or R1.Staff_Id = '')" +
                " Where R1.Rule_Id = " + Rule_Id + "";
        List ruleStaffList = eliteBean.chaxun_sql(ruleStaffSQL, "dataSource");

        Map ruleStaffMap = ruleStaffList.get(0);
        log.debug("ruleStaffMap:    " + ruleStaffMap);
        String ruleStaff = ruleStaffMap.get("ruleStaff");
        log.debug("ruleStaff:    " + ruleStaff);

        //处理Assign_Num
        def selectassignnumSQL = "select case when count(*)=0 then 0 else  round(sum(assign_num)/count(*)) end as assignnum from hst_rule_issue_control  Where Rule_Id = " + Rule_Id + "  And Assign_Date = Date_Format(Now(), '%Y-%m-%d') and channel='" + channel + "'";
        def selectassignnumresult = eliteBean.chaxun_sql(selectassignnumSQL, "dataSource");
        def assignnum = 0;
        if (selectassignnumresult.size() > 0) {
            assignnum = selectassignnumresult.get(0).get("assignnum");
        }
        log.debug("assignnum:    " + assignnum);
        // 2-将不在下发规则表中不存在的坐席补充，防止中途规则配置的人或组修改添加
        String insertStaffSQL = "Insert Into Hst_Rule_Issue_Control" +
                "  (Rule_Id, Staff_Id, Assign_Date, Assign_Num,assign_yynum, Last_Check_Time,channel)" +
                "  Select " + Rule_Id + ", Staff_Id, Date_Format(Now(), '%Y-%m-%d'), '" + assignnum + "', 0, Now(),'" + channel + "'" +
                "    From Staff" +
                "   Where Find_In_Set(Staff_Id, '" + ruleStaff + "') > 0" +
                "     And Staff_Id Not In (Select Staff_Id" +
                "                            From Hst_Rule_Issue_Control" +
                "                           Where Rule_Id = " + Rule_Id + "" +
                "                             And Assign_Date = Date_Format(Now(), '%Y-%m-%d') And channel='" + channel + "' )";
        int newStaffNum = eliteBean.update(insertStaffSQL, "dataSource");

        log.debug("newStaffNum:" + newStaffNum);

        // 3-将不需要不满足下发的坐席删除，防止中途规则配置的人或组删除
        String deleteStaffSQL = "Delete From Hst_Rule_Issue_Control" +
                " Where Staff_Id Not In" +
                "       (Select Staff_Id" +
                "          From Staff" +
                "         Where Find_In_Set(Staff_Id, '" + ruleStaff + "') > 0" +
                "   And ((auto_allocation = 0) " +
                " 	or (auto_allocation = 1 And starttime>now() And endtime>now() And starttime is not null And endtime is not null)" +
                " 	or (auto_allocation = 1 And starttime<now() And endtime<now() And starttime is not null And endtime is not null))" +
                "   And Workstatus = 'ONLINE')" +
                "   And Rule_Id = " + Rule_Id + "" +
                "   And Assign_Date = Date_Format(Now(), '%Y-%m-%d')";
        int deleteStaffNuM = eliteBean.update(deleteStaffSQL, "dataSource");
        log.debug("newStaffNum:" + deleteStaffNuM);
        return reFlag;
    }
}
